package elitech.vietnam.weatherfashion.backgroundtask;

import java.io.IOException;
import java.util.Calendar;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.widget.Toast;
import elitech.vietnam.weatherfashion.R;
import elitech.vietnam.weatherfashion.WFApplication;
import elitech.vietnam.weatherfashion.config.GlobalValue;
import elitech.vietnam.weatherfashion.dto.MemberDTO;
import elitech.vietnam.weatherfashion.service.ImageUploader;
import elitech.vietnam.weatherfashion.service.PHPSoapServiceCaller;

public class NewPostTask extends AsyncTask<String, Integer, Boolean> {

	private static final String MEMBER_FOLDER = "member_image/";
	private ProgressDialog pDialog;

	private Context context;

	public NewPostTask(Context context) {
		this.context = context;
		pDialog = new ProgressDialog(context);
		pDialog.setCancelable(false);
	}

	@Override
	protected Boolean doInBackground(String... params) {
		String name = params[1];
		String mem_pic = MEMBER_FOLDER + name;

		ImageUploader imageUploader = new ImageUploader();

		boolean uploadOk = false;
		uploadOk = imageUploader.upload(params[0], name);
		PHPSoapServiceCaller appService = new PHPSoapServiceCaller();
		if (uploadOk) {
			MemberDTO user = GlobalValue.getInstance(context).readUserInfo();
			int memID = user.getId();
			Calendar cal = Calendar.getInstance();
			int ngay = cal.get(Calendar.DATE);
			int thang = cal.get(Calendar.MONTH) + 1;
			int nam = cal.get(Calendar.YEAR);
			String content = params[2];
			String title = user.getMemberName() + " Style "
					+ cal.getTime().toString();
			int i;
			try {
				i = appService.createNewPost(memID, nam, thang, ngay, title,
						"0", "", mem_pic, content);
			} catch (IOException e) {
				i = -1;
			}
			uploadOk = !(i < 0);
		}
		if (uploadOk) {
			WFApplication.getInstance().stylerAllData = null;
		}
		return uploadOk;
	}

	@Override
	protected void onPreExecute() {
		super.onPreExecute();
		pDialog.setTitle(context.getString(R.string.processing));
		pDialog.setMessage(context.getString(R.string.please_wait_));
		pDialog.show();
	}

	@Override
	protected void onPostExecute(Boolean result) {
		super.onPostExecute(result);
		pDialog.dismiss();
		if (result) {
			Toast.makeText(context,
					context.getString(R.string.newpost_success),
					Toast.LENGTH_SHORT).show();
		} else
			Toast.makeText(context, context.getString(R.string.newpost_failed),
					Toast.LENGTH_SHORT).show();
		((Activity) context).setResult(Activity.RESULT_OK);
		((Activity) context).finish();

		context = null;
		pDialog = null;
	}
}
